package com.zzr.demo.redis.service.impl;

import com.google.common.collect.Sets;
import com.zzr.demo.redis.service.LikesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.startup.CopyParentClassLoaderRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.flyway.FlywayDataSource;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author: xiaomi
 * @date: 2021/10/8
 * @description:
 */
@Service
@Slf4j
public class LikesServiceImpl implements LikesService {

    final String LIKES_KEY = "likes::set";

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void likes(String paperId, String userId) {
        SetOperations<String, String> opsForSet = stringRedisTemplate.opsForSet();
        String key = LIKES_KEY + paperId;
        Long add = opsForSet.add(key, userId);
        log.info("key:{},点赞成功标志：{}", key, add);
    }

    @Override
    public void unlike(String paperId, String userId) {
        SetOperations<String, String> opsForSet = stringRedisTemplate.opsForSet();
        String key = LIKES_KEY + paperId;
        Long add = opsForSet.remove(key, userId);
        log.info("key:{},取消点赞 成功标志：{}", key, add);
    }

    @Override
    public Set<String> getLikesUsers(String paperId) {
        SetOperations<String, String> opsForSet = stringRedisTemplate.opsForSet();
        String key = LIKES_KEY + paperId;
        Set<String> members = opsForSet.members(key);
        log.info(members.toString());
        return members;
    }

    @Override
    public long getLikesCount(String paperId) {
        SetOperations<String, String> opsForSet = stringRedisTemplate.opsForSet();
        String key = LIKES_KEY + paperId;
        Long size = opsForSet.size(key);
        log.info("size:{}", size);
        return size;
    }
}
